package com.yjz.jvm.juc.Lock.ReentrantLockLearn;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Target {
    private int count = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void increase() {
        lock.lock();
        try {
            while (count == 2) {
                condition.await();  //当前线程进入aqs等待队列
            }
            count++;
            System.out.println(Thread.currentThread().getName() + ":" + count);
            condition.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void decrease() {
        lock.lock();
        try {
            while (count == 0) {
                condition.await();  //当前线程进入aqs等待队列
            }
            count--;
            System.out.println(Thread.currentThread().getName() + ":" + count);
            //唤醒线程Increase，Increase线程从aqs等待队列进入同步队列
            condition.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    /**
     * 响应线程中断学习
     *
     * @throws InterruptedException
     */
    public void say() throws InterruptedException {
        //线程响应中断
        if (Thread.interrupted()) {
            System.out.println(Thread.currentThread().getName()+" 开始响应中断");
            throw new InterruptedException();
        }
        System.out.println("没有中断");
    }

    public static void main(String[] args) {

        Thread t = new Thread(() -> {
            try {
                new Target().say();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        t.start();
        //模拟外部某个场景，需要将线程中断
        if (3 > 2) {
            t.interrupt();
        }

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
